const Ret = require("../Ret") ,
    { RequestCache } = require("../RequestCache") ,
    { RequestParser } = require("../RequestParser")

function isHaveAction( ctx ){
    
}

module.exports = async function( ctx , next ) {

    const app = this 
    if( !app.RequestCache ) app.RequestCache = new RequestCache()
    if( !app.RequestParser ) app.RequestParser = new RequestParser()

    //format request 
    const requestBody = app.RequestParser.values( ctx )
    ctx.request.ps = requestBody.ps
    ctx.request.pag = requestBody.pag 

    //cahced
    const isNeedCached = app.RequestCache.isNeedCached( ctx )
    if( isNeedCached ){
        const cacheRet = await app.RequestCache.value( ctx , requestBody )
        if( cacheRet ){
            ctx.body = cacheRet 
            return 
        }
    }

    //在使用mongodb时候，直接使用参数会导致注入问题，删除原生解析防止直接使用这些参数进行序列化
    delete ctx.request.body 
    delete ctx.request.query 
    //404 

    await next() 
    let retBody = ctx.body ? ctx.body : {}
    //TODO 由于无法确定是否继承至同一个对象，兼容处理，通过简单是否包含 code 字段判断是否为Ret体
    // if( !(retBody instanceof Ret )) {
    //     retBody = Ret.succ( retBody ) 
    // }
    if( !isRetObject( retBody ) )
        retBody = Ret.succ( retBody )

    ctx.body = retBody
    //加入缓存
    if( isNeedCached ){
        app.RequestCache.cached( ctx , requestBody , retBody )
    }

}

function isRetObject( obj ){
    //不考虑code值为数字0的情况
    return obj["code"] || obj["code"] == 0 ? true : false 
}